package br.uvv.Web.Servlet;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;

import javax.faces.context.FacesContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.primefaces.model.StreamedContent;

//import br.uvv.Util.FacesUtil;

@SuppressWarnings("all")
public class ImagemMemoriaSistemaServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
	private static final int DEFAULT_BUFFER_SIZE = 10240; // 10KB.
	
	public ImagemMemoriaSistemaServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	// imagemServlet?id=999&icon=true
	private void processRequest(HttpServletRequest request, HttpServletResponse response) {
		BufferedInputStream input = null;
		BufferedOutputStream output = null;
		try {
			String sistemaId = request.getParameter("image");
			Boolean tipo = false;
			if (sistemaId == null){
				sistemaId = request.getParameter("icon");
				tipo = true;
			}
			
			if (sistemaId == null) {
				response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
				return;
			}
			
//			FacesContext context = FacesUtil.getFacesContext(request, response);
			
			//Configurando a Resposta
			response.reset();
			response.setBufferSize(DEFAULT_BUFFER_SIZE);
			response.setContentType("image/jpeg");
//			response.setHeader("Content-Disposition", "inline; filename=\"" + sistemaInstance.getNome() + "\"");
			InputStream img = null;
			StreamedContent imagem = null; 
//				img = new ByteArrayInputStream(sistemaInstance.getImagem());
//				imagem = new DefaultStreamedContent(img,"image/jpeg");
//				response.setHeader("Content-Length", String.valueOf(sistemaInstance.getImagem().length));
			
//			input = new BufferedInputStream(imagem.getStream(), DEFAULT_BUFFER_SIZE);
//			output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);

			byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
			int length;
			while ((length = input.read(buffer)) > 0) {
				output.write(buffer, 0, length);
			}
		} catch (Exception e){
			e.printStackTrace();
		} finally {
			close(output);
			close(input);
		}
	}
	
	 private static void close(Closeable resource) {
        if (resource != null) {
            try {
                resource.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}